#!/user/bin/env python3
# -*- coding: utf-8 -*-

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt

# filename = r'd:/data/chessboard.png'
filename1 = r'd:/data/left01.jpg'
filename2 = r'd:/data/left02.jpg'

src1 = cv.imread(filename1)
src2 = cv.imread(filename2)


# 创建ORB特征检测器
sift = cv.xfeatures2d.SIFT_create()
# src1 = cv.cvtColor(src1, cv.COLOR_BGR2GRAY)
# src2 = cv.cvtColor(src2, cv.COLOR_BGR2GRAY)
kp1, des1 = sift.detectAndCompute(src1, None)
kp2, des2 = sift.detectAndCompute(src2, None)
# sift1 = cv.xfeatures2d.SIFT_create()
# 暴力匹配
bf = cv.DescriptorMatcher_create(cv.DescriptorMatcher_BRUTEFORCE)
matches = bf.match(des1,des2)
# 绘制匹配
matches = sorted(matches, key = lambda x:x.distance)
result = cv.drawMatches(src1, kp1, src2, kp2, matches[:15], None)
cv.imshow("orb-match", result)


#Harris角点检测
gray = cv.cvtColor(src1, cv.COLOR_BGR2GRAY)
gray = np.float32(gray)
dst = cv.cornerHarris(gray,2,3,0.04)
dst = cv.dilate(dst,None)
src1[dst>0.01 * dst.max()] = [0,0,255]
cv.imshow('corners',src1)


#FAST角点检测
fast = cv.FastFeatureDetector_create()

keypoints = fast.detect(src1, None)
imgs = cv.drawKeypoints(src1, keypoints, outImage=src1, color=(0, 0, 255))

print("Thereshold:", fast.getThreshold())
print("nonmaxSuppression:", fast.getNonmaxSuppression())
print("neighborhood:", fast.getType())
print("Total keypoints with nonmaxSuppression:", len(keypoints))
# 使用非最大值抑制的结果
cv.imshow('fast', imgs)


def cv_show(name, img):
    cv.imshow(name, img)
    cv.waitKey(0)
    cv.destroyAllWindows()


# cv_show('img1',img1)
# cv_show('img2',img2)

sift = cv.xfeatures2d.SIFT_create()

kp1, des1 = sift.detectAndCompute(src1, None)
kp2, des2 = sift.detectAndCompute(src2, None)

bf = cv.BFMatcher(crossCheck=True)

# 1对1匹配
# matches = bf.match(des1,des2)
# matches = sorted(matches,key=lambda x:x.distance)
# img3 = cv.drawMatches(img1,kp1,img2,kp2,matches[:10],None,flags=2)
# cv_show('img3',img3)

# k对最佳匹配
bf = cv.BFMatcher()
matches = bf.knnMatch(des1, des2, k=2)
good = []

for m, n in matches:
    if m.distance < 0.75 * n.distance:
        good.append([m])

img3 = cv.drawMatchesKnn(src1, kp1, src2, kp2, good, None, flags=2)
cv_show('img3',img3)

cv.waitKey(0)
cv.destroyAllWindows()